﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace PlanetViewer
{
    class WaterVertexGroup
    {
        public List<VertexPositionColor> SurfaceVertices;
        public List<VertexPositionColor> FloorVertices;

        public VertexPositionColor[] Vertices;
        public int[] Indices;

        public int _Length;

        public WaterVertexGroup()
        {
            SurfaceVertices = new List<VertexPositionColor>();
            FloorVertices = new List<VertexPositionColor>();
        }

        public bool ProcessLists()
        {
            _Length = SurfaceVertices.Count - 1;
            if (_Length < 2) return false;

            int nTris = 2 * _Length - 2;
            int nInds = 3 * nTris;

            Vertices = new VertexPositionColor[2 * _Length];
            Indices = new int[nInds];

            SurfaceVertices.CopyTo(Vertices);
            FloorVertices.CopyTo(Vertices, _Length + 1);

            int[][] indMat = CreateWaterIndexMatrix(_Length);

            Indices[0] = indMat[0][0];
            Indices[1] = indMat[1][0];
            Indices[2] = indMat[1][1];

            for (int i = 1; i < _Length - 1; i++)
            {
                int j = 3 + 6 * (i - 1);

                Indices[j] = indMat[i][0];
                Indices[j + 1] = indMat[i + 1][0];
                Indices[j + 2] = indMat[i + 1][1];

                Indices[j + 3] = indMat[i][0];
                Indices[j + 4] = indMat[i][1];
                Indices[j + 5] = indMat[i + 1][1];
            }

            Indices[nInds - 3] = indMat[_Length - 1][0];
            Indices[nInds - 2] = indMat[_Length - 1][1];
            Indices[nInds - 1] = indMat[_Length][0];

            return true;
        }

        private int[][] CreateWaterIndexMatrix(int length)
        {
            int[][] indMat = new int[length + 1][];

            for (int i = 0; i <= length; i++)
            {
                int[] sp = new int[2];

                sp[0] = i;
                sp[1] = i + length;

                indMat[i] = sp;
            }

            return indMat;
        }
    }
}
